const express = require("express");
const db = require("../config");

const orderRouter = express.Router();

/* 获取所有订单 */
orderRouter.get('/getAllOrder', (req, res) => {
    const sql = "SELECT o.*,i.goodsId,i.goodsName,i.goodsImg,i.size,i.color,i.price,i.num FROM db_order o JOIN db_orderitems i ON i.order_id=o.orderId ORDER BY o.orderId";
    db.query(sql, (err, result) => {
        if (err) return res.fail(err.message);
        if (result.length <= 0) return res.fail("获取订单失败，请重试");

        // 将结果按订单分组
        const orders = {};
        result.forEach(row => {
            if (!orders[row.orderId]) {
                // 创建新订单对象
                orders[row.orderId] = {
                    orderId: row.orderId,
                    orderNum: row.orderNum,
                    userId: row.userId,
                    total: row.total,
                    amount: row.amount,
                    method: row.method,
                    name: row.name,
                    phone: row.phone,
                    address: row.address,
                    Logistics_status: row.Logistics_status,
                    orderTime: row.orderTIme,
                    state: row.state,
                    items: []  // 初始化商品数组
                };
            }

            // 添加商品信息
            orders[row.orderId].items.push({
                goodsId: row.goodsId,
                goodsName: row.goodsName,
                goodsImg: row.goodsImg,
                size: row.size,
                color: row.color,
                price: row.price,
                num: row.num
            });
        });

        // 将对象转换为数组
        const orderList = Object.values(orders);

        res.send({
            status: 0,
            message: "获取订单成功",
            data: orderList
        });
    });
});


/* 删除订单 */
orderRouter.post('/delOrder', (req, res) => {
    const sql = "update db_order set state=0 where orderNum=?";
    db.query(sql, req.body.orderNum, (err, result) => {
        if (err) return res.fail(err.message);
        if (result.affectedRows !== 1) return res.fail("删除订单失败，请重试");
        res.send({
            status: 0,
            message: "删除订单成功"
        })
    })

});

/* 查找某个人的所有订单 */
orderRouter.get('/getOrder', (req, res) => {
    const sql = "SELECT o.*,i.goodsId,i.goodsName,i.goodsImg,i.size,i.color,i.price,i.num FROM db_order o JOIN db_orderitems i ON i.order_id=o.orderId WHERE o.userId=?;";
    db.query(sql, req.query.userId, (err, result) => {
        if (err) return res.fail(err.message);
        if (result.length <= 0) return res.fail("查询订单失败，请重试");
        res.send({
            status: 0,
            message: "查询订单成功",
            data: result
        })
    })
});

/* 查找某个商品的所有订单 */
orderRouter.get('/getGoodsOrder', (req, res) => {
    const sql = "SELECT o.*,i.goodsId,i.goodsName,i.goodsImg,i.size,i.color,i.price,i.num FROM db_order o JOIN db_orderitems i ON i.order_id=o.orderId WHERE i.goodsId=?;";
    db.query(sql, req.body.goodsId, (err, result) => {
        if (err) return res.fail(err.message);
        if (result.length <= 0) return res.fail("查询订单失败，请重试");
        res.send({
            status: 0,
            message: "查询订单成功",
            data: result
        })
    })

});

/* 生成订单 */
orderRouter.post('/addOrder', (req, res) => {
    const { orderNum, userId, total, amount, method, name, phone, address, Logistics_status, items } = req.body;
    console.log(typeof items);

    // 检查是否有商品数据
    if (!items || !Array.isArray(items)) {
        return res.fail("请提供商品信息");
    }

    const sql = "insert into db_order(orderNum,userId,total,amount,method,name,phone,address,Logistics_status) values(?,?,?,?,?,?,?,?,?)";
    db.query(sql, [orderNum, userId, total, amount, method, name, phone, address, Logistics_status], (err, result) => {
        if (err) return res.fail(err.message);
        if (result.affectedRows !== 1) return res.fail("生成订单失败，请重试");
        const orderId = result.insertId;

        // 计数器，用于检查所有商品是否都插入成功
        let successCount = 0;

        // 遍历所有商品并插入
        items.forEach((item, index) => {
            const { goodsId, goodsName, goodsImg, size, color, price, num } = item;
            const sql_item = "insert into db_orderitems(order_id,goodsId,goodsName,goodsImg,size,color,price,num) values(?,?,?,?,?,?,?,?)";

            db.query(sql_item, [orderId, goodsId, goodsName, goodsImg, size, color, price, num], (err, result) => {
                if (err) {
                    // 如果有错误，直接返回错误信息
                    return res.fail(err.message);
                }

                successCount++;

                // 当所有商品都处理完成后才返回成功
                if (successCount === items.length) {
                    res.send({
                        status: 0,
                        message: "生成订单成功",
                        data: {
                            orderId: orderId
                        }
                    });
                }
            });
        });
    });
});

/* 修改订单物流状态 */
orderRouter.post('/upOrder', (req, res) => {
    const sql = "UPDATE db_order SET Logistics_status=? where orderNum=?;";
    db.query(sql, [req.body.Logistics_status, req.body.orderNum], (err, result) => {
        if (err) return res.fail(err.message);
        if (result.affectedRows !== 1) return res.fail("更新订单失败，请重试");
        res.send({
            status: 0,
            message: "更新订单成功"
        })
    })

});

// 添加获取单个订单详情的接口
orderRouter.get('/getOrderDetail', (req, res) => {

    const { orderNum } = req.query;
    const sql = "SELECT o.*,i.goodsId,i.goodsName,i.goodsImg,i.size,i.color,i.price,i.num FROM db_order o JOIN db_orderitems i ON i.order_id=o.orderId WHERE orderNum=? ORDER BY o.orderId";

    db.query(sql, [orderNum], (err, result) => {
        if (err) return res.fail(err.message);
        if (result.length <= 0) {
            return res.fail('订单不存在');
        }

        res.send({ status: 0, message:"查询成功",data: result });
    });




});


module.exports = { orderRouter };